using Consul;
using System.Diagnostics;

namespace WebApp8.Client.Services
{
    public class ServiceDiscovery
    {
        private readonly IConsulClient _consulClient;

        public ServiceDiscovery(string consulAddress = "http://localhost:8500")
        {
            Console.WriteLine($"Initializing ServiceDiscovery with Consul address: {consulAddress}");
            _consulClient = new ConsulClient(cfg =>
            {
                cfg.Address = new Uri(consulAddress);
            });
        }

        public async Task<Uri?> GetServiceUrl(string serviceName)
        {
            try
            {
                Console.WriteLine($"Attempting to discover service: {serviceName}");
                
                // 获取所有服务
                var services = await _consulClient.Agent.Services();
                Console.WriteLine($"Total registered services: {services.Response.Count}");
                foreach (var svc in services.Response)
                {
                    Console.WriteLine($"Found service - ID: {svc.Key}, Name: {svc.Value.Service}, Address: {svc.Value.Address}, Port: {svc.Value.Port}");
                }

                // 获取健康的服务实例
                var healthyServices = await _consulClient.Health.Service(serviceName, tag: null, passingOnly: true);
                Console.WriteLine($"Healthy instances for {serviceName}: {healthyServices.Response.Count()}");
                
                var service = healthyServices.Response.FirstOrDefault();
                if (service == null)
                {
                    Console.WriteLine($"No healthy instances found for service: {serviceName}");
                    return null;
                }

                var serviceUri = new Uri($"http://{service.Service.Address}:{service.Service.Port}");
                Console.WriteLine($"Found service URL: {serviceUri}");
                return serviceUri;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error discovering service: {ex.Message}");
                Console.WriteLine($"Stack trace: {ex.StackTrace}");
                throw;
            }
        }
    }
} 